package rs.networx.servlets;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Properties;
import java.util.Random;

import javax.ejb.EJB;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import rs.networx.dao.ActivationDao;
import rs.networx.dao.PersonDao;

import rs.networx.entity.Activation;
import rs.networx.entity.Person;
import rs.networx.util.ErrorMessages;

public class RegistrationServlet extends HttpServlet {
	private static final long serialVersionUID = -5511815453441345595L;

	@EJB
	private PersonDao personDao;
	
	@EJB
	private ActivationDao activationDao;
	
	private String username;
	private String password;
	private String name;
	private String surname;
	private String dateOfBirth;
	private String sex;
	private String city;
	private String education;
	private String employment;
	private String webAdress;
	private String picture;
	
	private Person personToRegister;
	private Activation activationForPersonToRegister;
	
	private long activationCode;
	
	private boolean pass1;
	private boolean pass2;
	/* (non-Javadoc)
	 * @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
	 */
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		System.out.println("Servlet: REGISTRATION Loaded");
		//super.doGet(req, resp); TODO 
		resp.setContentType("text/html; charset=UTF-8");
		req.setCharacterEncoding(resp.getCharacterEncoding());
		HttpSession session = req.getSession(true);
		
		username = req.getParameter("SignUpPersonalProfileUsername");
		password = req.getParameter("SignUpPersonalProfilePassword");
		name = req.getParameter("SignUpPersonalProfileName");
		surname = req.getParameter("SignUpPersonalProfileSurname");
		dateOfBirth = req.getParameter("SignUpPersonalProfileDateOfBirth");
		sex = req.getParameter("SignUpPersonalProfileSex");
		city = req.getParameter("SignUpPersonalProfileCity");
		education = req.getParameter("SignUpPersonalProfileEducation");
		employment = req.getParameter("SignUpPersonalProfileEmployment");
		webAdress = req.getParameter("SignUpPersonalProfileWebAdress");
		if (sex.equalsIgnoreCase("male")) {
			picture = "/male.png";
		}else {
			picture = "/female.jpg";
		}
		
		System.out.println("username: " + username + 
						   "password: " + password +
						   "name: " + name +
						   "surname: " + surname + 
						   "dateOfBirth: " + dateOfBirth +
						   "sex: " + sex +
						   "city: " + city +
						   "education: " + education +
						   "employment: " + employment +
						   "webAdress: " + webAdress);
		
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd/MM/yyyy");
		
		pass1 = personDao.checkUsernameExistance(username);
		
		if(pass1 == true){
			// znaci da se dati username vec postoji u bazi...
			session.setAttribute("loginStatus", ErrorMessages.USERNAME_ALREADY_IN_USE);
			
			req.getRequestDispatcher("WelcomePage.jsp").forward(req, resp);
			return;
		}else if(pass1 == false){
			
			try {
				personToRegister = new Person(name, surname, simpleDateFormat.parse(dateOfBirth), sex, username, password, 
						city, webAdress, education, employment, picture);
				personToRegister.setActivated(false);
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			// save in database without picture...
			personDao.persist(personToRegister);
			
			// pravimo aktivaciju datog potencijalnog novog korisnika...
			activationCode = generateActivationCode();
			activationForPersonToRegister = new Activation(activationCode, personToRegister);
			
			activationDao.persist(activationForPersonToRegister);
			
			// sada saljemo activaton code na mail...
			System.out.println("Sending activation...");
			System.out.println(personToRegister.getId() + " , " + activationCode);
			
			pass2 = sendActivation(username, personToRegister.getId(), activationCode);
			
			if(pass2 == true){
				// sve je proslo ok...		
				req.getRequestDispatcher("SuccessfullRegistration.jsp").forward(req, resp);
				return;
			}else if(pass2 == false){
				// doslo je do greske, recimo email nije validan(ne postoji)...
				req.getRequestDispatcher("RegistrationError.jsp").forward(req, resp);
				return;
			}
		}
	}

	/* (non-Javadoc)
	 * @see javax.servlet.http.HttpServlet#doPost(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
	 */
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		//super.doPost(req, resp);
		doGet(req, resp);
	}

	private long generateActivationCode() {
		
		Random generator = new Random();
		long code = generator.nextLong();
		
		//pravimo pozitivne vrednosti
		if(code <0){
			code *= -1;
		}
		return code;		
	}
	
	//--------------------------------------------------------------------------------------------------------------------------------------------------
	private boolean sendActivation(String emailTo, Integer personID, long activationCode){
		
		boolean result = false;
		Properties props = new Properties();
		
		props.put("mail.smtp.host", "smtp.gmail.com");
		props.put("mail.smtp.socketFactory.port", "465");
		props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
		props.put("mail.smtp.auth", "true");
		props.put("mail.smtp.port", "465");

		Session session = Session.getInstance(props, new javax.mail.Authenticator() { // getDefaultInstance()...
			
			protected PasswordAuthentication getPasswordAuthentication() {
				return new PasswordAuthentication("thesnpmbs2", "humanity1");
			}
		});

		try {
			Message message = new MimeMessage(session);
			
			message.setFrom(new InternetAddress("thesnpmbs2@gmail.com"));
			message.setRecipients(Message.RecipientType.TO,
					InternetAddress.parse(emailTo));
			message.setSubject("Registration Activation Link");
			message.setText("This is registration confirmation for The Social Network Project.\n" +
					"Go to link below to activate your account: \n" +
					"http://localhost:8080/networx/ActivationServlet?personID=" + personID + 
					"&activationCode=" + activationCode);

			Transport.send(message);

			System.out.println("Verifycation: sent");
			result = true; 
		} catch (MessagingException e) {
			// ako nesto nije proslo kako treba, recimo ako email nije validan(ne postoji)...
			result = false;
			//throw new RuntimeException(e);
		}
		return result;
	}


}
